package com.bm.greeting.service.impl;

import com.bm.greeting.service.SendMailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;

@Component
public class SendMail implements SendMailService {

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;


    /**
     * 邮箱群发消息
     *
     * @param subject     主题
     * @param message     消息
     * @param sourceEmail 源电子邮件
     */
    public void sendMassMessage(String subject, String message, String[] sourceEmail) {
        ArrayList<String[]> objects = new ArrayList<>();
        objects.add(sourceEmail);

        for (String[] object : objects) {
            try {
                MimeMessage mimeMessage = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
                helper.setFrom(from);       //发送方邮件名
                helper.setTo(object);         //接收方邮件地址
                helper.setSubject(subject);     //邮件标题
                helper.setText(message, true);   //邮件内容，是否为html格式
                mailSender.send(helper.getMimeMessage());
            } catch (javax.mail.MessagingException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 邮箱发送消息
     *
     * @param subject     主题
     * @param message     消息
     * @param sourceEmail 源电子邮件
     */
    public void sendMessage(String subject, String message, String sourceEmail) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setFrom(from);       //发送方邮件名
            helper.setTo(sourceEmail);         //接收方邮件地址
            helper.setSubject(subject);     //邮件标题
            helper.setText(message, true);   //邮件内容，是否为html格式
            mailSender.send(helper.getMimeMessage());
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
        }
    }

}
